package com.ww.springboot.boot.javabase.proxy.cglib;

import net.sf.cglib.proxy.*;

import java.lang.reflect.Method;

public class EnhancerCallbackHelper {

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Car.class);

        //根据方法参数 自定义相应的增强方式 这个挺有用的--
        CallbackHelper helper = new CallbackHelper(Car.class, new Class[0]) {
            @Override
            protected Object getCallback(Method method) {
                if (method.getReturnType() == void.class) {
                    return (MethodInterceptor) (obj, method1, args1, methodProxy) -> {
                        System.out.println("before invocation");
                        Object res = methodProxy.invokeSuper(obj, args1);
                        System.out.println("after invocation");
                        return res;
                    };
                } else if (method.getReturnType() == String.class) {
                    return (FixedValue) () -> "a hacked car";
                } else return NoOp.INSTANCE;
            }
        };

        enhancer.setCallbacks(helper.getCallbacks());
        enhancer.setCallbackFilter(helper);

        Car car = (Car) enhancer.create();
        car.print();
        System.out.println(car.getId());
        System.out.println(car.getName());
    }

    static class Car {
        static int index = 0;

        int id;

        Car() {
            id = index++;
        }

        String getName() {
            return "car";
        }

        int getId() {
            return id;
        }

        void print() {
            System.out.println("I am a car");
        }

    }
}